<template>
  <div class="login-container">
    <div class="login-box">
      <h2>银行登录系统</h2>
      <div class="input-group">
        <label>卡号：</label>
        <input type="text" v-model="cardno" placeholder="请输入银行卡号" @keyup.enter="handleLogin">
      </div>
      <div class="input-group">
        <label>密码：</label>
        <input type="password" v-model="password" placeholder="请输入密码" @keyup.enter="handleLogin">
      </div>
      <button @click="handleLogin" :disabled="loading">
        {{ loading ? '登录中...' : '登录' }}
      </button>
    </div>
  </div>
</template>

<script>
import md5 from 'md5'

export default {
  name: 'Login',
  data() {
    return {
      cardno: '',
      password: '',
      loading: false
    }
  },
  created() {
    // this.$store.commit('clearUserInfo');
  },
  methods: {
    async handleLogin() {
      if (!this.cardno || !this.password) {
        this.$message.warning('请输入卡号和密码')
        return;
      }
      this.loading = true; // 设置加载状态

      try {
        const res = await this.$axios({
          method: 'post',
          url: 'localhost:81/bank/login',
          data:{
            cardno: this.cardno,
            password: md5(this.password)
          } // 使用完整URL
            
        });

        if (res.data.code === 0) {
          // 保存token和用户信息到vuex
          // this.$store.commit('setUserInfo', {
          //   token: res.data.data.token,
          //   userInfo: res.data.data.userInfo
          // });

          // 设置axios请求头
          // this.$axios.defaults.headers.common['Authorization'] = `Bearer ${res.data.data.token}`;

          this.$message.success('登录成功');

          // 使用 replace 而不是 push
          await this.$router.replace('/dashboard');
        } else {
          this.$message.error(res.data.msg || '登录失败')
        }
      } catch (error) {
        console.error('登录失败:', error);
        this.$message.error('登录失败，请重试')
      } finally {
        this.loading = false; // 无论成功失败都关闭加载状态
      }
    }
  }
}

</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-box {
  width: 400px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.input-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  color: #666;
}

input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover:not(:disabled) {
  background-color: #45a049;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.error-message {
  color: #f44336;
  margin-top: 10px;
  text-align: center;
}
</style>
